<script lang="ts" setup>
import type {Ref} from "vue";
import {onBeforeMount, ref} from "vue";
import {pageSession, deleteSession} from "@/api/session";
import type {PageSessionRequest} from "@/api/session";
import type {SessionResponse} from "@/api/session";
import {Search, Delete} from '@element-plus/icons-vue'
import {ElMessage} from "element-plus";

const sessionData: Ref<SessionResponse[]> = ref([])
const pageSessionRequest: Ref<PageSessionRequest> = ref({
  pageIndex: 1,
  pageSize: 10
})
const total: Ref<number> = ref(0)

onBeforeMount(() => {
  pageClient();
})

function pageClient(): void {
  pageSession(pageSessionRequest.value).then(res => {
    total.value = Number(res.data.total);
    sessionData.value = res.data.body;
  })
}

function currentChange(value: number): void {
  pageSessionRequest.value.pageIndex = value
  pageClient()
}

function removeClient(clientId: string): void {
  deleteSession(clientId).then(res => {
    if (res.data.body) {
      ElMessage.success("删除成功")
    } else {
      ElMessage.error("删除失败")
    }
    pageClient()
  })
}

</script>

<template>
  <el-row>
    <el-input v-model="pageSessionRequest.clientId" placeholder="客户端 id" clearable/>
    <el-button type="primary" :icon="Search" @click="pageClient">搜索</el-button>
  </el-row>
  <el-table max-height="60vh" :data="sessionData" empty-text="暂无数据">
    <el-table-column min-width="100px" prop="clientId" label="客户端 id"/>
    <el-table-column min-width="100px" prop="username" label="用户名"/>
    <el-table-column min-width="100px" prop="status" label="状态"/>
    <el-table-column min-width="100px" prop="keepAliveTime" label="心跳"/>
    <el-table-column min-width="100px" prop="isCleanSession" label="clean start"/>
    <el-table-column min-width="100px" prop="connectTime" label="连接时间"/>
    <el-table-column min-width="100px" label="操作">
      <template #default="scope">
        <el-popconfirm title="确认要剔除此客户端吗？" confirm-button-text="确认" cancel-button-text="取消"
                       confirm-button-type="danger" @confirm="removeClient(scope.row.clientId)">
          <template #reference>
            <el-button type="danger" size="small" plain :icon="Delete">剔除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination layout="prev, pager, next" :page-size="pageSessionRequest.pageSize" :total="total"
                 :current-page="pageSessionRequest.pageIndex" @current-change="currentChange" hide-on-single-page/>
</template>

<style scoped>
.el-input {
  width: 230px;
  margin-right: 10px;
  margin-bottom: 10px;
}

.el-table {
  width: 100%;
  margin-top: 10px;
}

.el-pagination {
  margin-top: 20px;
}
</style>